/**
 * Created by chenzheyu on 2017/4/7.
 */
$(function () {
    /****表格*/
    $.fn.Order = function (options) {
        var me = this;//window
        //DOM容器对象，类似MX框架中的$e
        var $e = $(this);

        $e.find('.CustomOrder').remove();
        //配置样式-----------------------------------

        options.overflowX = options.overflowY || true;
        options.overflowY = options.overflowX || false;

        var OrderH = options.OrderH ? options.OrderH : 'auto';
        var Select = options.select || false;
        //配置样式-----------------------------------
        if (options.data) {//判断是否存在数据
            var data = options.data;
            var CustomOrder = $('<div style="min-height:' + options.OrderH + '; padding-bottom: 150px;" class="CustomOrder"></div>').css({
                'overflow-y': options.overflowY ? 'auto' : 'none',
                'overflow-x': options.overflowX ? 'none' : 'auto'
            });
            $e.append(CustomOrder);
            var TableVal = $('<table class="OrderTable"></table>');
            CustomOrder.append(TableVal);
            var Table = $e.find('table');
            Table.append($('<thead></thead>'));
            var Thead = Table.find('thead');
            Thead.append($('<tr></tr>'));
            var TheadVal = '';
            if (Select) {//如果有选择
                TheadVal += '<th class="OrderSelect">' + '<label><span>全选</span><input type="checkbox" class="SelectAll"></label>' + '</th>';
            }
            for (var key in data.Thead) {
                TheadVal += '<th>' + data.Thead[key] + '</th>';
            }
            Thead.find('tr').append(TheadVal);
            Table.append('<tbody></tbody>');
            var Tbody = Table.find('tbody');
            if (data.Tbody.length > 0) {//判断有没有数据
                for (var i = 0; i < data.Tbody.length; i++) {
                    (function () {
                        var index = i;
                        var TbodyVal = $('<tr></tr>');
                        if (Select) {//如果有选择
                            TbodyVal.append($('<td></td>').html('<input type="checkbox" class="SelectCheckbox">'))
                        }

                        for (var key in data.Tbody[index]) {
                            (function () {
                                var Key = key;
                                var td = $('<td></td>');
                                if (Key === 'id') {
                                    if (typeof data.Tbody[index]['id'] == "object") {
                                        var Data = new Object();
                                        for (keys in data.Tbody[index]['id']) {
                                            (function () {
                                                var Key = keys;
                                                Data[Key] = data.Tbody[index]['id'][Key]
                                            })()
                                        }
                                        TbodyVal.data({'data': Data, 'index': index});
                                    } else {
                                        TbodyVal.data({'id': data.Tbody[index]['id'], 'index': index});
                                    }

                                } else if (Key == 'PullDownAction') {
                                    td.Select(data.Tbody[index].PullDownAction);
                                    TbodyVal.append(td);
                                } else if (typeof data.Tbody[index][Key] == 'object' && Key == 'ButtonAction') {

                                    var ButtonAction = $('<span class="ButtonAction"></span>');
                                    ButtonAction.text(data.Tbody[index][Key].name).on('click', function () {
                                        data.Tbody[index][Key].Action($(this));
                                    });
                                    td.append(ButtonAction);
                                    TbodyVal.append(td);
                                } else if (typeof data.Tbody[index][Key] == 'object') {
                                    td.append(data.Tbody[index][Key]);
                                    TbodyVal.append(td);
                                } else {
                                    td.append(data.Tbody[index][Key]);
                                    TbodyVal.append(td);
                                }
                            })()
                        }
                        Tbody.append(TbodyVal);
                    })()

                }
                var SelectData = [];
                var SelectCheckbox = $('.SelectCheckbox');
                $('.SelectAll').on('click', function () {//返回选择index
                    SelectData = [];
                    if ($(this).is(':checked')) {
                        for (var i = 0; i < SelectCheckbox.length; i++) {
                            SelectCheckbox.eq(i).prop("checked", true);
                            SelectData.push(i);
                        }
                    } else {
                        for (var i = 0; i < SelectCheckbox.length; i++) {
                            SelectCheckbox.eq(i).prop("checked", false);
                            SelectData = [];
                        }
                    }
                    options.selectchange(SelectData)
                });

                for (var i = 0; i < SelectCheckbox.length; i++) {//返回选择index
                    SelectCheckbox.eq(i).data('index', i);
                    SelectCheckbox.eq(i).on('click', function () {
                        SelectData = [];
                        var SelectState = false;

                        function SelectStates() {
                            for (var j = 0; j < SelectCheckbox.length; j++) {
                                if (SelectCheckbox.eq(j).is(':checked')) {
                                    SelectState = true;
                                } else {
                                    SelectState = false;
                                    return;
                                }
                            }
                        }

                        for (var j = 0; j < SelectCheckbox.length; j++) {
                            if (SelectCheckbox.eq(j).is(':checked')) {
                                SelectData.push(SelectCheckbox.eq(j).data('index'))
                            }
                        }
                        SelectStates();
                        options.selectchange(SelectData);
                        SelectData = [];


                        if (SelectState) {
                            $('.SelectAll').prop("checked", true)
                        } else {
                            $('.SelectAll').prop("checked", false)
                        }
                    })
                }
            } else {
                $e.find('.CustomOrder').append('<div class="placeholder">没有查询到相应数据</div>');
            }
        }
    };
    /**下拉菜单*/
    $.fn.Select = function (options) {
        var me = this;//window
        var $e = $(this);//自己
        var CustomSelect = $('<div class="CustomSelect"></div>');

        var Placeholder = $('<div class="Placeholder CustomClear"></div>');
        var PlaceholderText = $('<div class="PlaceholderText"></div>');
        var jiantou = $('<div class="CustomSelectJianTou"></div>');
        jiantou.append('<span class="MewEle MewEle-jiantou "></span>');
        if (options.Default) {
            PlaceholderText.append(options.Default.name).on('click', function () {
                if (options.Default.action) {
                    options.Default.action(CustomSelect)
                }
            })
        } else {
            PlaceholderText.text('选择操作')
        }
        Placeholder.append(PlaceholderText);
        Placeholder.append(jiantou);
        CustomSelect.append(Placeholder);
        $e.append(CustomSelect);
        var TableVal = CustomSelect;
        if (options.data) {
            var data = options.data;
            var CustomSelectUl = $('<ul></ul>');
            CustomSelect.append(CustomSelectUl);
            for (var i = 0; i < data.length; i++) {
                var OptionVal = '<li  >' + data[i].name + '</li>';
                CustomSelectUl.append(OptionVal);
            }
            jiantou.on('click', function (e) {
                e.stopPropagation();//阻止冒泡
                var CustomSelect = $('body .CustomSelect');
                for (var i = 0; i < CustomSelect.length; i++) {
                    (function () {
                        var index = i;
                        CustomSelect.eq(index).find('ul').attr('Action', 'false');
                    })()
                }
                if (CustomSelectUl.attr('Action') == 'false') {
                    CustomSelectUl.attr('Action', 'true');
                } else {
                    CustomSelectUl.attr('Action', '');
                }

            });

            var Option = CustomSelectUl.find('li');
            for (var i = 0; i < Option.length; i++) {
                (function () {
                    var index = i;
                    Option.eq(index).data('index', index);
                    Option.eq(index).on('click', function (e) {
                        var indexs = $(this).data('index');
                        e.stopPropagation();//阻止冒泡
                        if (data[indexs].action) {
                            data[indexs].action($(this));
                        } else if (options.ActionChange) {
                            options.ActionChange($(this).text())
                        }
                        CustomSelectUl.attr("Action", 'false');
                    })
                })()
            }

            if (options.UpShow) {
                CustomSelect.bind('click', function (e) {
                    e.stopPropagation();//阻止冒泡
                    var UlH = CustomSelectUl.css('height');
                    CustomSelectUl.css('top', '-' + UlH)
                })

            }
            $(document).click(function (e) {
                var _con = CustomSelect.find('ul'); // 设置目标区域
                if (!_con.is(e.target) && _con.has(e.target).length === 0) {
                    CustomSelectUl.attr('Action', '');
                }
            });
        }


    };
    /****模态窗口*/
    $.fn.ModalBox = function (options) {
        var $e = $(this) || $('body');
        options.OKHide = options.OKHide || false;
        options.CancelHide = options.CancelHide || false;
        options.inputNumberMin = options.inputNumberMin ||false;
        if (options) {
            var Data = options.data;
            var CustomModalBox = $('<div class="CustomModalBox"></div>');
            var CustomModalBoxlength = '' + ($('.CustomModalBox').length );
            CustomModalBox.attr('CustomModalBoxLength', CustomModalBoxlength);
             var NewCustomModalBox = $('.CustomModalBox[CustomModalBoxLength="' + CustomModalBoxlength + '"]');
            $e.append(CustomModalBox);


            var Modal = $('<div class="Modal"></div>');
            var Frame = $('<div class="Frame"></div>');
            var Title = $('<div class="Title"></div>').html('<h2>' + Data.Title + '</h2>');
            var Mid = $('<div class="Mid"></div>').html('<div class="MidContent"></div>');
            var Bottom = $('<div class="Bottom"></div>');
            var OKButton = $('<button class="OK" type="button">确定</button>');

            var CancelButton;
            if (!options.CancelHide) {
                CancelButton = $('<button class="Cancel" type="button">取消</button>');
                Bottom.append(CancelButton);
                CancelButton.on('click', function (e) {
                    e.stopPropagation();
                    if (Data.CancelChange) {
                        Data.CancelChange(CustomModalBox, Remove)
                    }
                    Remove()
                });
            }

            Frame.append(Title);
            Frame.append(Mid);

            Bottom.append(OKButton);
            Frame.append(Bottom);
            Modal.append(Frame);
            CustomModalBox.append(Modal);
            var MidContent = CustomModalBox.find('.MidContent');
            if (Data.Content.CustomOrder) {
                for (key in Data.Content) {
                    (function () {
                        var Key = key;
                        if (typeof Data.Content[Key] == 'object') {
                            if (Key == 'CustomOrder') {
                                var data = Data.Content[Key];
                                var ModalBoxOrder = $('<div class="ModalBoxOrder"></div>');
                                var AddCustomOrder = $('<div class="AddCustomOrder"></div>');
                                AddCustomOrder.Order(data);
                                ModalBoxOrder.append(AddCustomOrder);
                                MidContent.append(ModalBoxOrder)
                            } else {
                                MidContent.append(Data.Content[Key])
                            }
                        } else {
                            MidContent.append(Data.Content[Key])
                        }
                    })()
                }
            } else {
                MidContent.append(Data.Content)
            }


            function Remove() {
                CustomModalBox.remove()
            }

            OKButton.on('click', function (e) {

                e.stopPropagation();
                if (!options.CancelHide) {

                    if (Data.OkChange) {
                        Data.OkChange(CustomModalBox, Remove)

                    }

                    console.log(options.OKHide)
                    if (!options.OKHide) {
                        Remove()

                    }

                } else {

                    if (Data.OkChange) {
                        Data.OkChange(CustomModalBox);
                        Remove()
                    }
                }

            });


            if ($e.find('.CustomModalBox input').length >= 1) {
                var t = $e.find('.CustomModalBox input').eq(0).val();
                $e.find('.CustomModalBox input').eq(0).focus().val(t);
            } else if ($e.find('.CustomModalBox textarea').length >= 1) {
                var t = $e.find('.CustomModalBox textarea').eq(0).val();
                $e.find('.CustomModalBox textarea').eq(0).focus(t);
            }


            CustomModalBox.keyup(function (event) {
                switch (event.keyCode) {
                    case 27:
                        $e.find('.Cancel[type="button"]').click();
                        break;
                }
            })

        }
        if(!options.inputNumberMin){
            for(var i=0;i<$e.find('input[type="number"]').length;i++){
                (function () {
                    var index=i;
                    $e.find('input[type="number"]').eq(index).on('change',function () {
                        if($(this).val()<0){
                            $(this).val(0)
                        }
                    })
                })()
            }
        }


    };
    /**分页按钮*/
    $.fn.PagingMd = function (options) {
        var me = this;
        var $e = $(this);
        $e.find('.PagingMdPagingMd').remove();
//----------------------------配置函数-----------------
        //跳转页
        function PageNumberModule(i, action) {
            var indexs = i;
            var Item = '';
            Item = $('<span class="PageNumber"></span>').text(indexs).data('index', indexs).on('click', function () {
                data.change($(this).data('index'));
            });
            if (indexs == data.nowrows) {
                Item.attr('action', true)
            }
            PagingMdPagingMd.append(Item);
        }

//----------------------------配置函数-----------------
        if (options && options.data.total > 0) {
            var data = options.data;
            data.Pages = Math.ceil((data.total / data.rows));
            var PagingMdPagingMd = $('<div class="PagingMdPagingMd"></div>');
            $e.append(PagingMdPagingMd);
            if (data.total) {
                PagingMdPagingMd.append('<span class="NextTotal" >共' + data.total + '条</span>');
            }
            if (data.nowrows > 1) {
                PagingMdPagingMd.append('<span class="PreviousPage" aria-hidden="true">&laquo;</span>');
            }
            if (data.nowrows >= 1 && data.nowrows <= 3) {
                var Pages = data.Pages >= 5 ? 5 : data.Pages;
                for (var i = 1; i < Pages + 1; i++) {
                    PageNumberModule(i)
                }
            } else if (data.nowrows <= data.Pages && data.nowrows >= data.Pages - 2) {
                for (var i = (data.Pages - 4) == 0 ? 1 : data.Pages - 4; i <= data.Pages; i++) {
                    PageNumberModule(i)
                }
            } else {
                for (var i = data.nowrows - 2; i < data.nowrows + 3; i++) {
                    PageNumberModule(i)
                }
            }
            if (data.nowrows <= data.Pages - 1) {
                PagingMdPagingMd.append('<span class="NextPage"  aria-hidden="true">&raquo;</span>');
            }
            var PreviousPage = PagingMdPagingMd.find('.PreviousPage');
            PreviousPage.on('click', function () {
                var index = $e.find('.PageNumber[action="true"]').data('index');
                data.change(index - 1);
            });
            var NextPage = PagingMdPagingMd.find('.NextPage');
            NextPage.on('click', function () {
                var index = $e.find('.PageNumber[action="true"]').data('index');
                data.change(index + 1);
            })
        }
    };
    /**上传图片*/
    $.fn.UpLoading = function (options) {
        var me = this;
        var $e = $(this);
        var UpLimit = options.UpLimit;

        function SearchImage() {
            var UpImgItem = $e.find('.CustomUpLoading').find('.UpImgItem');
            var ImageArr = [];
            for (var i = 0; i < UpImgItem.length; i++) {
                (function () {
                    var index = i;
                    ImageArr.push(UpImgItem.eq(index).find('img').attr('src'))
                })()
            }
            return ImageArr;
        }

        function AddImage(url) {

            if (options.DefaultImage.length < UpLimit && $e.find('.CustomUpLoading').find('.UpImgItem').length + 1 < UpLimit) {
            } else {
                $e.find('#fileToUpload').remove();
            }
            var UpImgItem = $('<div class="UpImgItem"><img src="' + url + '"><span class="Delete"></span></div>');
            UpImgItem.find('.Delete').on('click', function (e) {
                e.stopPropagation();
                UpImgItem.remove();
                if (options.DefaultImage.length < UpLimit && $e.find('.CustomUpLoading').find('.UpImgItem').length + 1 <= UpLimit) {
                    if ($e.find('#fileToUpload').length == 0) {
                        UpLimitFn(true);
                    } else {
                        if (options.onChange) {
                            options.onChange(SearchImage())
                        }
                    }
                }
            });
            UpImgItem.on('click', function (e) {
                e.stopPropagation();
                var RawImageMod = $('<div class="RawImageMod"><div class="Mod"></div></div>');
                var RawImage = $('<div class="RawImage"><img src="' + $(this).find('img').attr('src') + '" ><span class="RawRaw"></span></div>');
                RawImageMod.append(RawImage);
                RawImage.find('.RawRaw').on('click', function () {
                    RawImageMod.remove();
                    if (options.onChange) {
                        options.onChange(SearchImage())
                    }
                });
                $(document).click(function (e) {
                    var _con = RawImage.find('.RawRaw');
                    if (!_con.is(e.target) && _con.has(e.target).length === 0) {
                        RawImageMod.remove();
                    }
                });
                $('body').append(RawImageMod)
            });
            UpImg.append(UpImgItem);

            options.onChange(SearchImage())
        }

        function UpLimitFn(state) {
            if (state) {

                var AddButton = $('<div id="fileToUpload" class="AddButton"><i>+</i></div>');
                CustomUpLoading.append(AddButton);

                var upload_container = document.createElement("div");
                upload_container.id = 'upload_container';
                $e[0].appendChild(upload_container);

                var uploader = new plupload.Uploader({
                    runtimes: 'html5,flash,silverlight,html4',
                    browse_button: 'fileToUpload', // you can pass an id...
                    container: document.getElementById('upload_container'),
                    url: options.url,
                    flash_swf_url: 'Moxie.swf',
                    silverlight_xap_url: 'Moxie.xap',
                    filters: {
                        max_file_size: '10mb',
                        mime_types: [
                            {title: "Image files", extensions: "jpg,gif,png"}
                        ]
                    },

                    init: {
                        PostInit: function () {
                        },
                        FilesAdded: function (up, files) {
                            up.start();
                        },
                        UploadProgress: function (up, file) {
                            //// console.log(file);
                        },
                        FileUploaded: function (up, file, info) {
                            // Called when file has finished uploading
                            // // console.log('[FileUploaded] File:', file, "Info:", info);
                            var url = eval('(' + info.response + ')').url;
                            AddImage(url)
                        },
                        Error: function (up, err) {
                            //// console.log(arguments);
                        }
                    }
                });

                uploader.init();


            }
        }


        if (options) {
            var CustomUpLoading = $('<div class="CustomUpLoading"></div>');
            $e.append(CustomUpLoading);
            if (options.DefaultImage.length + 1 <= options.UpLimit) {
                var UpImg = $('<div class="UpImg"></div>');
                CustomUpLoading.append(UpImg);
                for (var i = 0; i < options.DefaultImage.length; i++) {
                    AddImage(options.DefaultImage[i])
                }

                UpLimitFn(UpLimit)
            }

        }
    };
    /**查询框*/
    $.fn.SearchBox = function (options) {
        var me = this;
        var $e = $(this);
        if (options.data) {
            var SearchBox = $('<div class="SearchBox"></div>');
            $e.append(SearchBox)

        }
    };
    /**选项卡*/
    $.fn.OrderTabs = function (options) {
        var me = this;//window
        var $e = $(this);
        if (options) {
            var tabsDiv = $("<div class='CustomTabs'></div>");
            var data = options.data;

            var tabsUl = $("<ul class='CustomClear'></ul>");
            for (var i = 0; i < data.length; i++) {
                (function () {
                    var Oli = $('<li></li>');

                    if (data[i].data) {
                        var Obj = new Object();
                        for (var key in data[i].data) {
                            Obj[key] = data[i].data[key];
                        }
                        Obj['data'] = Obj;
                    }
                    Oli.data({'index': i});
                    Oli.on('click', function () {
                        var ali = tabsUl.find('li');
                        for (var j = 0; j < ali.length; j++) {
                            ali.eq(j).attr('action', false)
                        }
                        $(this).attr('action', true);
                        if (options.onChange) {
                            options.onChange(Oli.data())
                        }
                    });

                    if (data[i].url) {
                        if (data[i].action) {
                            if (data[i].badge) {
                                Oli.attr('action', 'true').append("<span>" + data[i].badge + "</span><a href='" + data[i].url + "'>" + data[i].name + "</a>");
                            } else {
                                Oli.attr('action', 'true').append("<a href='" + data[i].url + "'>" + data[i].name + "</a>");
                            }
                        } else {
                            if (data[i].badge) {
                                Oli.append("<span>" + data[i].badge + "</span><a href='" + data[i].url + "'>" + data[i].name + "</a>");
                            } else {
                                Oli.append("<a href='" + data[i].url + "'>" + data[i].name + "</a>");
                            }
                        }
                    } else {
                        if (data[i].action) {
                            if (data[i].badge) {
                                Oli.attr('action', 'true').append("<span><a>" + data[i].badge + "</span>" + data[i].name + "</a>");
                            } else {
                                Oli.attr('action', 'true').append("<a>" + data[i].name + "</a>");
                            }
                        } else {
                            if (data[i].badge) {
                                Oli.append("<span>" + data[i].badge + "</span><a>" + data[i].name + "</a>");
                            } else {
                                Oli.append("<a>" + data[i].name + "</a>");
                            }
                        }
                    }
                    tabsUl.append(Oli);
                })();

            }
            tabsDiv.append(tabsUl);
            $e.append(tabsDiv);
        }
    };
    /**Select 下拉框*/
    $.fn.DownPullSelect = function (options) {
        var me = this;//window
        var $e = $(this);//自己
        $e.find('.CustomDownPullSelect').remove();
        var CustomDownPullSelect = $('<div class="CustomDownPullSelect"></div>');
        $e.append(CustomDownPullSelect);
        var Select = $('<select class="Select"></select>').on("change", function () {
                options.onChange({val: $(this).val(), text: $(this).find('option[value="' + $(this).val() + '"]').text()});
            }
        );
        CustomDownPullSelect.append(Select);
        if (options) {
            var Data = options.data;
            for (var i = 0; i < Data.length; i++) {
                (function () {
                    var index = i;
                    var SelectOptions = $("<option></option>").text(Data[index].name).val(Data[index].Val);
                    Select.append(SelectOptions)
                })()
            }


            options.onChange({val: Select.val(), text: Select.find('option[value="' + Select.val() + '"]').text()});
        }

    };
    /**添加复制元素按钮*/
    $.fn.AddCopyButton = function (options) {
        var me = this;
        var $e = $(this);
        var CustomAddCopyButton = $('<div class="CustomAddCopyButton"></div>');
        $e.append(CustomAddCopyButton);
        if (options) {
            var Data = options.data;


            var RemoveBuuton = $('<div><span class="glyphicon glyphicon-minus"></span></div>').addClass('RemoveButton').on('click', function () {
                if (options.onChange) {
                    options.onChange($e)
                }
                CustomAddCopyButton.parent().parent().remove();
            });
            CustomAddCopyButton.append(RemoveBuuton);
        }
    };
    /**顶部消息浮窗*/
    $.fn.Overlays = function (options) {
        var me = this;
        var $e = $(this);
        var Overlays = $('<div class="CustomOverlays"></div>');
        var Content = $('<div class="OverlaysContent"></div>');
        Overlays.append(Content);
        $('body').append(Overlays);
        if (options) {
            var Data = options.data;
            var Text = $('<p class="Text"></p>').text(Data.text);
            var Icon;
            switch (Data.state) {
                case 'No':
                    Icon = $('<span class="MewEle MewEle-gantanhao NoIcon"></span>');
                    Content.attr('state', 'No');
                    break;
                case 'Ok':
                    Icon = $('<span class="MewEle MewEle-zhengque OkIcon"></span>');
                    Content.attr('state', 'Ok');
                    break;
                case 'Warn':
                    Icon = $('<span class="MewEle MewEle-wenhao WarnIcon"></span>');
                    Content.attr('state', 'Warn');
                    break;
                default:
                    Icon = '';
                    Content.attr('state', 'Default');
            }
            Content.append(Icon).append(Text);
            setTimeout(function () {
                Content.attr('show', 'true')
            }, 500);
            setTimeout(function () {
                Content.removeAttr('show');

                setTimeout(function () {
                    Overlays.remove()
                }, 400)
            }, 3000)

        }


    };
    /**面板模态*/
    $.fn.PanelModule = function (options) {
        var me = this;
        var $e = $(this);

        options.upload = options.upload || options.data.Title.onChange || true;//加载默认设置

        var UpLoadAnimate;
        var UpLoadAnimateState = true;
        var HintText = true;
        var successUpLoadState = false;

        function StopUpLoad(hint) {
            UpLoadAnimateState = false;
            HintText = hint || '您的网络去开小差了！';
        }

        function successUpLoad() {
            UpLoadAnimateState = false;
            successUpLoadState = true;
        }

        function AddUpLoad() {

            if (options.upload) {
                var Upload = $('<div class="Upload"></div>');
                var Icon = $('<span class="Icon"></span>').animate({
                    transform: 'translate(-50%,-50%)  scale(0,0)',
                    opacity: 0
                });
                var text = $('<span class="hint"></span>').removeAttr('show');
                Upload.append(Icon).append(text);
                CustomPanelModuleBody.append(Upload);
                Upload.attr('show', 'true');

                var Time = 0;
                var scale = 0;
                var opacity = 0;
                setTimeout(function () {
                    UpLoadAnimate = setInterval(function () {
                        if (UpLoadAnimateState) {
                            Time += 35;
                            scale += 1;
                            opacity += 0.05;
                            Icon.animate().css({
                                transform: 'translate(-50%,-50%)' + 'rotate(' + Time + 'deg)',
                                padding: scale + 'px',
                                opacity: opacity
                            });
                            scale >= 15 ? scale = 15 : null;
                            opacity >= 1 ? opacity = 1 : null;
                            if (Time >= 35 * (5000 / 29)) {
                                StopUpLoad()
                            }
                        } else {
                            Time -= 35;
                            scale -= 1;
                            opacity -= 0.05;
                            Icon.animate().css({
                                transform: 'translate(-50%,-50%)' + 'rotate(' + Time + 'deg)',
                                padding: scale + 'px',
                                opacity: opacity
                            });
                            scale <= 0 ? scale = 0 : null;
                            opacity <= 0 ? opacity = 0 : null;
                            if (Time <= 3500 && !successUpLoadState) {
                                text.text(HintText).attr('show', true);
                            } else {

                            }

                            if (Time <= 0) {
                                clearInterval(UpLoadAnimate);
                                if (successUpLoadState) {
                                    Upload.removeAttr('show');
                                    setTimeout(function () {
                                        CustomPanelModuleContent.attr('show', true);
                                    }, 280);
                                }
                            }
                        }
                    }, 29)
                }, 300);
            }


        }

        if (options) {
            var Data = options.data;
            var CustomPanelModule = $('<div class="CustomPanelModule"></div>');
            if (Data.AttachData && typeof Data.AttachData == 'object') {
                var data = new Object();
                for (key in Data.AttachData) {
                    data[key] = Data.AttachData[key];
                }
                CustomPanelModule.data('data', data)
            }
            $e.append(CustomPanelModule);
            var CustomPanelModuleHead = $('<div class="CustomPanelModuleHead"></div>').on('click', function (e) {
                e.stopPropagation();
                var CustomPanelModuleAll = $e.find('.CustomPanelModule');
                // CustomPanelModuleAll.find('.CustomPanelModuleContent').html('');
                CustomPanelModule.find('.CustomPanelModuleContent').removeAttr('show');
                var that = $(this).parent();
                for (var i = 0; i < CustomPanelModuleAll.length; i++) {
                    (function () {
                        var index = i;
                        CustomPanelModuleAll.eq(index).data('index', index);
                        CustomPanelModuleAll.eq(index).find('.CustomPanelModuleBody').find('.Upload').remove();
                    })();
                }
                for (var j = 0; j < CustomPanelModuleAll.length; j++) {
                    (function () {
                        var index=j;
                        if(index==that.data('index')){
                            if (CustomPanelModuleAll.eq(index).find('.CustomPanelModuleBody').attr('show')) {
                                CustomPanelModuleAll.eq(index).find('.CustomPanelModuleBody').removeAttr('show');
                                CustomPanelModuleAll.eq(index).find('.CustomPanelModuleBody').find('.Upload').remove();
                                CustomPanelModuleAll.eq(index).find('.CustomPanelModuleBody').find('CustomPanelModuleContent').html('');
                            } else {
                                CustomPanelModuleAll.eq(index).find('.CustomPanelModuleBody').attr('show', 'true');
                                if (options.upload) {
                                    UpLoadAnimateState = true;
                                    AddUpLoad();
                                    if (Data.Title.onChange) {
                                        Data.Title.onChange(CustomPanelModule, {
                                            StopUpLoad: StopUpLoad,
                                            successUpLoad: successUpLoad
                                        })
                                    }
                                }
                            }
                        }else {
                            CustomPanelModuleAll.eq(index).find('.CustomPanelModuleBody').removeAttr('show');
                            CustomPanelModuleAll.eq(index).find('.CustomPanelModuleBody').find('.Upload').remove();
                        }
                    })();
                }


            });
            CustomPanelModule.append(CustomPanelModuleHead);
            if (typeof Data.Title.content == 'object') {
                CustomPanelModuleHead.append(Data.Title.content);
            } else {
                var Title = $('<h2 class="text"></h2>').text(Data.Title.content);
                CustomPanelModuleHead.append(Title);
            }
            var CustomPanelModuleBody = $('<div class="CustomPanelModuleBody" ></div>');
            var CustomPanelModuleContent = $('<div class="CustomPanelModuleContent" ></div>');
            CustomPanelModuleBody.append(CustomPanelModuleContent);
            CustomPanelModule.append(CustomPanelModuleBody);
            if (typeof  Data.Tbody == 'object') {
                CustomPanelModuleContent.append(Data.Tbody)
            } else if (typeof  Data.Tbody == 'string') {
                var Text = $('<p class="text"></p>').text(Data.Tbody);
                CustomPanelModuleContent.append(Text);
            }


        }
    };
    /**按钮*/
    $.fn.ActionButtons = function (options) {
        var me = this;
        var $e = $(this);
        if (options) {
            var Data = options.data;
            var CustomActionButtons = $('<button class="CustomActionButtons"></button>');
            CustomActionButtons.on('click', function (e) {
                e.stopPropagation();
                if (options.onChange) {
                    options.onChange(CustomActionButtons)
                }
            });
            if (typeof  options.AttachData == "object") {
                var obj = new Object();
                for (key in options.AttachData) {
                    obj[key] = options.AttachData[key]
                }
                CustomActionButtons.data('data', obj)
            }
            var text = $('<span class="CustomActionButtonsText"></span>');
            var text1 = $('<span class="CustomActionButtonsText1"></span>');
            if (Data && typeof Data == 'string') {
                text.text(Data);
                text1.text(Data);
                CustomActionButtons.append(text);
                CustomActionButtons.append(text1)
            }
            $e.append(CustomActionButtons);
        }
    };
    /**可修改的input*/
    $.fn.ReviseInput = function (options) {
        var me = this;//window
        var $e = $(this);//jq本生
        var CustomInput = $("<div class='CustomInput CustomClear'></div>");
        $e.append(CustomInput);
        if (options) {
            var Data = options.data;
            var Input = $("<span class='CustomInputText'></span>").text(Data.fontName);
            var confirmButton = $("<span  class='CustomInputButn MewEle MewEle-bianji'></span>").on("click", function () {
                options.data.OkChange(Input.val())
            });
            CustomInput.append(Input);
            CustomInput.append(confirmButton);

        }
    };
    /**标签添加**/
    $.fn.AddLabel = function (options) {
        var me = this;//window
        var $e = $(this);//jq本生
        $e.find('.AddLabelModule').remove();
        var closeState = options.StopAction || true;
        var AddLimit = options.AddLimit || true;
        var AddLabelModule = $('<div class="CustomAddLabel CustomClear"></div>');
        $e.append(AddLabelModule);
        var LabelOccupied = $('<div class="LabelOccupied CustomClear"></div>');
        AddLabelModule.append(LabelOccupied);
        function LabelOccupieds(name, id) {
            var ItemLabe = $('<span class="LabelItem"><span class="LabelItemName">' + name + '</span><span class="LabelItemAction">X</span></div></span>');
            ItemLabe.data('id', id);
            function Remove() {
                ItemLabe.remove();
            }

            ItemLabe.find('.LabelItemAction').on('click', function () {
                if (closeState) {
                    Remove();
                    Data.placement.onChange(id)
                } else {
                    Data.placement.onChange(name, Remove)
                }
            });
            LabelOccupied.append(ItemLabe)
        }

        if (options) {
            var Data = options.data;
            //判断子是否有占位标签
            if (Data.placement.length >= 1) {
                for (var i = 0; i < Data.placement.length; i++) {
                    LabelOccupieds(Data.placement[i].name, Data.placement[i].id);
                }
            }

            if (AddLimit) {
                if (!options.StopAction) {
                    var AddLabelButon = $('<div class="AddLabelButon"><span class="AddLabelButonIcon">+</span></div>');
                    AddLabelButon.on('click', function () {
                        if (options.AddButtonAction) {
                            options.AddButtonAction()
                        }
                    });
                    AddLabelModule.append(AddLabelButon)
                }
            }


        }

    };
    /**单选按钮
     * */
    $.fn.RadioActionButtons = function (options) {
        var me = this;
        var $e = $(this);
        var CustomRadioAction = $('<span class="CustomRadioAction"></span>');
        $e.append(CustomRadioAction);
        if (options) {
            var Data = options.data;
            var RadioAction = $('<input type="radio" name="' + Data.name + '">');
            RadioAction.on('click', function () {
                if (options.onChange) {
                    options.onChange(CustomRadioAction)
                }
            });
            CustomRadioAction.append(RadioAction);
        }

    };
    /**小时选择
     * */
    $.fn.DateTimeSelect = function (options) {
        var me = this;
        var $e = $(this);
        $e.on('click', function () {
            $('body').find('.CustomDateTimeSelect').remove();
            DateTimeSelectClick()
        });

        function DateTimeSelectClick() {
            var h = '';
            var m = '';
            var left = $e.offset().left;
            var top = $e.offset().top + $e.height();
            var CustomDateTimeSelect = $('<div class="CustomDateTimeSelect" style="left: ' + left + 'px; top: ' + (top + 10) + 'px"><div class="CustomDateTimeSelectMod"></div></div>');

            function Minutes() {
                var MinutesSelect = $('<div class="MinutesSelect"><h2 class="Title">选择分</h2></div>');

                for (var i = 0; i < 60; i += options.MinutesInterval ? options.MinutesInterval : 5) {
                    (function () {
                        var index = i;
                        if (index < 10) {
                            index = '0' + i
                        }
                        var MinutesItme = $('<span class="MinutesItme">' + index + '</span>').data('time', index);
                        MinutesItme.on('click', function () {
                            var m = $(this).data('time');
                            $e.val(h + ':' + $(this).data('time'));
                            MinutesSelect.remove();
                            CustomDateTimeSelect.remove();
                            options.onChange()
                        });
                        MinutesSelect.append(MinutesItme)
                    })()
                }
                CustomDateTimeSelect.append(MinutesSelect);


            }

            function Hour() {


                var HourSelect = $('<div class="HourSelect"><h2 class="Title">选择时</h2></div>');

                for (var i = 0; i < 24; i++) {
                    (function () {
                        var index = i;
                        if (index < 10) {
                            index = '0' + i
                        }
                        var HourItme = $('<span class="HourItme">' + index + '</span>').data('time', index);
                        HourItme.on('click', function () {
                            h = $(this).data('time');
                            $e.val($(this).data('time') + ':00');
                            HourSelect.remove();
                            Minutes();
                        });
                        HourSelect.append(HourItme)
                    })()
                }
                CustomDateTimeSelect.append(HourSelect);

            }

            Hour();
            $('body').append(CustomDateTimeSelect);

            CustomDateTimeSelect.find('.CustomDateTimeSelectMod').on('click', function () {
                CustomDateTimeSelect.remove()
            })

        }


    };
    /**徽章*
     */
    $.fn.Badge = function (options) {
        var me = this;
        var $e = $(this);


        if (options) {
            var Data = options.data;
            var CustomBadge = $('<span class="CustomBadge"></span>');
            var CustomBadgeContent = $('<span class="CustomBadgeContent"></span>');
            CustomBadge.append(CustomBadgeContent);
            switch (Data.state) {
                case 'No':
                    CustomBadgeContent.append(Data.text).attr('state', 'No');
                    break;
                case 'Ok':
                    CustomBadgeContent.append(Data.text).attr('state', 'Ok');
                    break;
                case 'Warn':
                    CustomBadgeContent.append(Data.text).attr('state', 'Warn');
                    break;
                default:
                    CustomBadgeContent.append(Data.text).attr('state', 'Default');
            }

            if ($e.context) {
                $e.append(CustomBadge)
            } else {
                return CustomBadge
            }
        }
    };
    /**时间轴*
     *
     */
    $.fn.OrderStatus = function (option) {
        var me = this;//window
        var $e = $(this);//jq本生
        if (option) {
            $e.append('<div class="CustomOrderStatus"></div>');
            var CustomOrderStatus = $e.find('.CustomOrderStatus');
            var CustomSpline = $("<div class='CustomSpline'></div>");
            var StateUl = $("<ul class='clearfix'></ul>");
            StateUl.append(CustomSpline);
            switch (option.status) {
                case 0:
                    CustomSpline.css("width", "100px");

                    break;
                case 10:
                    CustomSpline.css("width", "300px");
                    break;
                case 20:
                    CustomSpline.css("width", "600px");
                    break;
                case 35:
                    CustomSpline.css("width", "800px");
                    break;
                case 45:
                    CustomSpline.css("width", "1000px");
                    break
            }
            if (option.state) {
                for (var i = 0; i < option.state.length; i++) {
                    if (!option.state[i].stateTime) {
                        option.state[i].stateTime = "";
                    }
                    var StateLi =
                        $("<li><div class='circle'><div class='StateTime'>" + option.state[i].stateTime +
                            "</div><div class='StateName'>" + option.state[i].stateName + "</div></div></li>");
                    StateUl.append(StateLi);
                    CustomOrderStatus.append(StateUl);
                }
            }
        }
    };
    /****车辆信息追踪
     * */
    $.fn.TraceInformation = function (options) {
        var me = this;//window
        //DOM容器对象，类似MX框架中的$e
        var $e = $(this);

        function getLocalTime(nS) {
            return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
        }

        if (options) {
            var CustomTrace = $("<div class='CustomTrace'></div>");
            $e.append(CustomTrace);
            var Trace = $e.find(".CustomTrace");
            Trace.append($("<div class='TraceHeader clearfix'></div><div class='TraceCont clearfix'></div>"));
            var TraceCont = Trace.find(".TraceCont");
            TraceCont.append($("<div class='TraceTime'></div><div class='TraceMessage'></div>"));
            var TraceTime = TraceCont.find(".TraceTime");
            var TraceMessage = TraceCont.find(".TraceMessage");
            TraceTime.append("<div class='TimeTitle'>时间</div>");
            TraceTime.append("<ul class='TraceTimeUl'></ul>");
            TraceMessage.append("<div class='MessageTitle'>跟踪信息</div>");
            TraceMessage.append("<ul class='TraceMessageUl'></ul>");
            var TraceMessageUl = TraceMessage.find(".TraceMessageUl");
            var TraceTimeUl = TraceTime.find(".TraceTimeUl");
            var TraceTimeLi = "";
            var TraceMessageLi = "";
            for (var i = 0; i < options.data.length; i++) {
                TraceTimeLi += '<li>' + getLocalTime(options.data[i].created) + '</li>';
                TraceMessageLi += "<li>" + options.data[i].memo + "</li>";
                TraceTimeUl.html(TraceTimeLi);
                TraceMessageUl.html(TraceMessageLi)
            }

        }

    };
    /**
     * 树状TAB
     * */
    $.fn.TreeView=function (options) {
        var me=this;
        var $e=$(this);
        $e.find('CustomTreeView').remove();
        if(options){
            var Data=options.data;
            var CustomTreeView=$('<div class="CustomTreeView"></div>');

            if(Data.length>0){

                var topState=true;

                function AddUl(parent,Data,sequence) {

                    var TreeViewUl=$('<ul class="TreeViewUl"></ul>');
                    if(topState){
                        topState=false;
                        TreeViewUl.addClass('TreeViewUlTop')
                    }


                    for(var i=0;i<Data.length;i++){
                        (function () {
                            var index=i;
                            var TreeViewLi=$('<li class="TreeViewLi"></li>');
                            var TreeViewLiContent=$('<div class="TreeViewLiContent"></div>');
                            var TreeViewLiContentAction=$('<span class="TreeViewLiContentAction MewEle"></span>');
                            var TreeViewLiText=$('<sapn class="TreeViewLiText"></sapn>');
                            if(sequence){
                                TreeViewLiContent.css({padding:'0 '+25*(sequence+1)+'px'+' 0 '+25*(sequence+1)+'px'});
                            }
                            TreeViewLiContent.append(TreeViewLiContentAction);
                            TreeViewLiText.append(Data[index].content);
                            TreeViewLiContent.append(TreeViewLiText);
                            TreeViewLi.append(TreeViewLiContent);
                            TreeViewLiContent.on('click',function (e) {
                                e.stopPropagation();
                                if(Data[index].onChange){
                                    Data[index].onChange(TreeViewLiText,Data[index].subjoin)
                                }

                                var aTreeViewLiContent=$e.find('.TreeViewLiContent');
                                for(var j=0;j<aTreeViewLiContent.length;j++){
                                    (function () {
                                        var index=j;
                                        aTreeViewLiContent.eq(index).removeClass('TreeViewLiContentAC');
                                    })();

                                }
                                $(this).addClass('TreeViewLiContentAC');
                                TreeViewLi.find('.TreeViewUl').eq(0).toggleClass('TreeViewUlShow');
                                TreeViewLiContentAction.toggleClass('TreeViewLiContentActionShow');
                            });


                            if(Data[index].child){
                                TreeViewLiContentAction.addClass(' MewEle-jiantou');
                                AddUl(TreeViewLi,Data[i].child,sequence+1)
                            }
                            TreeViewUl.append(TreeViewLi);
                        })()
                    }

                    parent.append(TreeViewUl)
                }
                AddUl(CustomTreeView,Data,0)
            }


            $e.append(CustomTreeView);
        }



    };
    /**时间字符转时间戳*/
    $.fn.Timestamp = {
        /**时间转时间戳*/
        DateTimestamp: function (stringTime) {
            // var stringTime = "2017-04-06 06:00";
            var timestamp2 = Date.parse(new Date(stringTime));
            timestamp2 = timestamp2 / 1000;
//          2014-07-10 10:21:12的时间戳为：1404958872
//          // console.log(stringTime + "的时间戳为：" + timestamp2);
            return timestamp2
        },
        /**时间戳转时间*/
        TimestampDate: function (stringTimestamp) {
            var date = new Date(parseInt(stringTimestamp) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
            var year = date.split('/')[0];
            date = date.replace(year, '');
            date = date.replace('/', '');
            var month = date.split('/')[0];
            date = date.replace(month, '');
            date = date.replace('/', '');
            var day;
            var hour;
            var minute;

            if (date.indexOf('上午') >= 0) {
                day = date.split('上午')[0];

                date = date.replace(day, '');
                date = date.split('上午')[1];

                hour = date.split(':')[0];
                if (hour < 10) {
                    hour = '0' + hour;
                    date = date.replace(hour, '');
                } else if (hour == 12) {
                    hour = '00';
                    date = date.replace(12, '');
                }
                minute = date.split(':')[1];
            } else if (date.indexOf('下午') >= 0) {
                day = date.split('下午')[0];
                date = date.replace(day, '');
                date = date.split('下午')[1];
                date = date.replace('下午', '');
                hour = (parseInt(date.split(':')[0]) + 12) + '';
                date = date.replace(hour, '');
                minute = date.split(':')[1];
            }

            date = year + '-' + month + '-' + day + "" + hour + ':' + minute;
            if (date.split('--')) {
                date = date.split('--')[0]
            };
            // console.log(date)
            return date
        },
        /**时间戳转换天数*/
        DayCalculate: function (stringTimestamp) {
            var result;
            if (stringTimestamp > 0) {
                var Timestamp = stringTimestamp;
                var t = parseInt(Timestamp / 86400);
                Timestamp = Timestamp - (t * 86400);
                var h = parseInt(Timestamp / 3600);
                Timestamp = Timestamp - (h * 3600);
                var m = parseInt(Timestamp / 60);
                var s = Timestamp - (m * 60);
                result = t + '天' + h + '时' + m + '分' + s + '秒';
            } else {
                result = '已到期'
            }

            return result
        }
    };
    /**判断电话号码*/
    $.fn.Method = {
        MovePhone: function (Phone) {
            var state = /^1[34578]\d{9}$/.test(Phone);
            return state
        },
        SeatPhone: function (Phone) {
            var state = /^0\d{2,3}-\d{7,8}(-\d{1,6})?$/.test(Phone);
            return state
        }

    };
    /**抽取Url地址上的传参*/
    $.fn.AcquireUrlParameter = function () {
        var url = location.search; //获取url中"?"符后的字串
        var UrlObj = new Object();
        if (url.indexOf("?") != -1) {
            url = url.replace('?', '');
            url = url.split('&');
            for (var i = 0; i < url.length; i++) {
                (function () {
                    var index = i;
                    var urls = url[index];
                    UrlObj[urls.split('=')[0]] = urls.split('=')[1];
                })()
            }
        } else {
            UrlObj = '当前URL无传参！'
        }
        return UrlObj;
    };
    /**判断车牌号
     * */
    $.fn.isVehicleNumber = function (options) {
        var result = false;
        if (options.length == 7) {
            var express = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;
            result = express.test(options);
        }
        return result;
    };
    /**解决 浮点计算BUG*/
    $.fn.Calculation = {
        /**加法运算*/
        accAdd: function (arg1, arg2) {
            var r1, r2, m;
            try {
                r1 = arg1.toString().split(".")[1].length
            } catch (e) {
                r1 = 0
            }
            try {
                r2 = arg2.toString().split(".")[1].length
            } catch (e) {
                r2 = 0
            }
            m = Math.pow(10, Math.max(r1, r2))
            return ((arg1 * m + arg2 * m) / m).toFixed(2);
        },
        /**减法运算*/
        Subtr: function (arg1, arg2) {
            var r1, r2, m, n;
            try {
                r1 = arg1.toString().split(".")[1].length
            } catch (e) {
                r1 = 0
            }
            try {
                r2 = arg2.toString().split(".")[1].length
            } catch (e) {
                r2 = 0
            }
            m = Math.pow(10, Math.max(r1, r2));
            //last modify by deeka
            //动态控制精度长度
            n = (r1 >= r2) ? r1 : r2;
            return ((arg1 * m - arg2 * m) / m).toFixed(2);
        },
        /**除法运算*/
        accDiv: function (arg1, arg2) {
            var t1 = 0, t2 = 0, r1, r2;
            try {
                t1 = arg1.toString().split(".")[1].length
            } catch (e) {
            }
            try {
                t2 = arg2.toString().split(".")[1].length
            } catch (e) {
            }
            with (Math) {
                r1 = Number(arg1.toString().replace(".", ""));
                r2 = Number(arg2.toString().replace(".", ""));
                return (r1 / r2) * pow(10, t2 - t1);
            }
        },
        /**乘法运算*/
        accMul: function (arg1, arg2) {
            var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
            try {
                m += s1.split(".")[1].length
            } catch (e) {
            }
            try {
                m += s2.split(".")[1].length
            } catch (e) {
            }
            return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
        }

    };
    /** 上传图片 ajax插件*/
    $.extend({
        createUploadIframe: function (id, uri) {
            //create frame
            var frameId = 'jUploadFrame' + id;
            var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
            if (window.ActiveXObject) {
                if (navigator.userAgent.split(";")[1].toLowerCase().indexOf("msie 9.0") == "-1" ? false : true) {
                    iframeHtml = document.createElement('iframe');
                    iframeHtml.id = frameId;
                    iframeHtml.name = frameId;
                } else {
                    if (typeof uri == 'boolean') {
                        iframeHtml += ' src="' + 'javascript:false' + '"';

                    }
                    else if (typeof uri == 'string') {
                        iframeHtml += ' src="' + uri + '"';

                    }
                    iframeHtml += ' />';
                }
            }
            else {
                iframeHtml += ' />';
            }
            jQuery(iframeHtml).appendTo(document.body);

            return jQuery('#' + frameId).get(0);
        },
        createUploadForm: function (id, fileElementId, data) {
            //create form
            var formId = 'jUploadForm' + id;
            var fileId = 'jUploadFile' + id;
            var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
            if (data) {
                for (var i in data) {
                    jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
                }
            }
            var oldElement = jQuery('#' + fileElementId);
            var newElement = jQuery(oldElement).clone();
            jQuery(oldElement).attr('id', fileId);
            jQuery(oldElement).before(newElement);
            jQuery(oldElement).appendTo(form);


            //set attributes
            jQuery(form).css('position', 'absolute');
            jQuery(form).css('top', '-1200px');
            jQuery(form).css('left', '-1200px');
            jQuery(form).appendTo('body');
            return form;
        },

        ajaxFileUpload: function (s) {
            // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
            s = jQuery.extend({}, jQuery.ajaxSettings, s);
            var id = new Date().getTime()
            var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data) == 'undefined' ? false : s.data));
            var io = jQuery.createUploadIframe(id, s.secureuri);
            var frameId = 'jUploadFrame' + id;
            var formId = 'jUploadForm' + id;
            // Watch for a new set of requests
            if (s.global && !jQuery.active++) {
                jQuery.event.trigger("ajaxStart");
            }
            var requestDone = false;
            // Create the request object
            var xml = {}
            if (s.global)
                jQuery.event.trigger("ajaxSend", [xml, s]);
            // Wait for a response to come back
            var uploadCallback = function (isTimeout) {
                var io = document.getElementById(frameId);
                try {
                    if (io.contentWindow) {
                        xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
                        xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;

                    } else if (io.contentDocument) {
                        xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
                        xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
                    }
                } catch (e) {
                    jQuery.handleError(s, xml, null, e);
                }
                if (xml || isTimeout == "timeout") {
                    requestDone = true;
                    var status;
                    try {
                        status = isTimeout != "timeout" ? "success" : "error";
                        // Make sure that the request was successful or notmodified
                        if (status != "error") {
                            // process the data (runs the xml through httpData regardless of callback)
                            var data = jQuery.uploadHttpData(xml, s.dataType);
                            // If a local callback was specified, fire it and pass it the data
                            if (s.success)
                                s.success(data, status);

                            // Fire the global callback
                            if (s.global)
                                jQuery.event.trigger("ajaxSuccess", [xml, s]);
                        } else
                            jQuery.handleError(s, xml, status);
                    } catch (e) {
                        status = "error";
                        jQuery.handleError(s, xml, status, e);
                    }

                    // The request was completed
                    if (s.global)
                        jQuery.event.trigger("ajaxComplete", [xml, s]);

                    // Handle the global AJAX counter
                    if (s.global && !--jQuery.active)
                        jQuery.event.trigger("ajaxStop");

                    // Process result
                    if (s.complete)
                        s.complete(xml, status);

                    jQuery(io).unbind()

                    setTimeout(function () {
                        try {
                            jQuery(io).remove();
                            jQuery(form).remove();

                        } catch (e) {
                            jQuery.handleError(s, xml, null, e);
                        }

                    }, 100)

                    xml = null

                }
            }
            // Timeout checker
            if (s.timeout > 0) {
                setTimeout(function () {
                    // Check to see if the request is still happening
                    if (!requestDone) uploadCallback("timeout");
                }, s.timeout);
            }
            try {

                var form = jQuery('#' + formId);
                jQuery(form).attr('action', s.url);
                jQuery(form).attr('method', 'POST');
                jQuery(form).attr('target', frameId);
                if (form.encoding) {
                    jQuery(form).attr('encoding', 'multipart/form-data');
                }
                else {
                    jQuery(form).attr('enctype', 'multipart/form-data');
                }
                jQuery(form).submit();

            } catch (e) {
                jQuery.handleError(s, xml, null, e);
            }

            jQuery('#' + frameId).load(uploadCallback);
            return {
                abort: function () {
                }
            };

        },

        uploadHttpData: function (r, type) {
            var data = !type;
            data = type == "xml" || data ? r.responseXML : r.responseText;
            // If the type is "script", eval it in global context
            if (type == "script")
                jQuery.globalEval(data);
            // Get the JavaScript object, if JSON is used.
            if (type == "json") {
                data = data.replace(/<(\/)?pre[^>]*>/g, '');
                eval("data = " + data);
            }


            // evaluate scripts within html
            if (type == "html")
                jQuery("<div>").html(data).evalScripts();

            return data;
        },

        handleError: function (s, xhr, status, e) {
// If a local callback was specified, fire it
            if (s.error) {
                s.error.call(s.context || s, xhr, status, e);
            }

            // Fire the global callback
            if (s.global) {
                (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);
            }
        }
    });

});